<?php

namespace Common\Model;
use Think\Model\RelationModel;
class UsersModel extends RelationModel {
    /**
     * 自动验证
     * self::EXISTS_VALIDATE 或者0 存在字段就验证（默认）
     * self::MUST_VALIDATE 或者1 必须验证
     * self::VALUE_VALIDATE或者2 值不为空的时候验证
     */
    protected $_validate = array(
        array('username', 'require', '用户名不能为空！', 0), //默认情况下用正则进行验证
        array('sex', 'require', '性别不能为空！', 0), //默认情况下用正则进行验证
        array('age', 'require', '年龄不能为空！', 0), //默认情况下用正则进行验证
        array('verify', 'require', '验证码不能为空！'), //默认情况下用正则进行验证
        array('verify', 'check_verify', '验证码错误', 0, 'callback'),// 判断验证码是否正确
        //array('username', 'require', '用户名不能为空！'), //默认情况下用正则进行验证
        array('email', '', '该邮箱已被占用', 0, 'unique', 1), // 新增的时候email字段是否唯一
        array('username', '', '该用户名已被占用', 0, 'unique', 1), // 新增的时候username字段是否唯一
        //array('mobile', '', '该手机号码已被占用', 0, 'unique', 1), // 新增的时候mobile字段是否唯一
        // 正则验证密码 [需包含字母数字以及@*#中的一种,长度为6-22位]
        array('password', '/^([a-zA-Z0-9@*#]{6,22})$/', '密码格式不正确,请重新输入！', 0),
        array('repassword', 'password', '确认密码不正确', 0, 'confirm'), // 验证确认密码是否和密码一致
        array('email', 'email', '邮箱格式不正确') // 内置正则验证邮箱格式
        //array('mobile', '/^1[34578]\d{9}$/', '手机号码格式不正确', 0), // 正则表达式验证手机号码



    );
    /**
     * 自动完成
     */
    protected $_auto = array (
        array('password', 'md5', 3, 'function') , // 对password字段在新增和编辑的时候使md5函数处理
        array('regdate', 'time', 1, 'function'), // 对regdate字段在新增的时候写入当前时间戳
        array('regip', 'get_client_ip', 1, 'function'),// 对regip字段在新增的时候写入当前注册ip地址
        array('mobile', 0),
        array('status', 1),
        array('permission', 1)//普通注册用户权限字段1，组织者添加的用户权限字段0
    );

    protected function check_verify($code, $id = 1){
        $verify = new \Think\Verify();
        if ($verify->check($code, $id) == true){
            return true;
        }
        else{
            return false;
        }
    }

    protected $_link = array(
        'orgnizer_info'=>array(
            'mapping_type' => self::HAS_ONE,
            'class_name'    =>'orgnizeruserclass',
            'foreign_key' => 'uid'
        ),
        'orgnizer_userquizlist' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name'    =>'orgnizer_userquizlist',
            'foreign_key' => 'uid'
        ),
        'calc_result' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name'    =>'calc_result',
            'foreign_key' => 'user_id'
        ),
        'user_answer' => array(
            'mapping_type' => self::HAS_MANY,
            'class_name'    =>'user_answer',
            'foreign_key' => 'user_id'
        )
    );

    /**
     * 更新用户信息，返回操作结果信息数组
     * @param $uid
     * @param $data
     * @return array
     */

    public function updateUserInfo($uid, $data)
    {
        $user = $this;

        if($user->create($data)){
            if($data['password'])
                $data['password'] = md5($data['password']);
            $user->where(['uid' => $uid])->save($data);
            $rs['msg'] = '用户信息修改成功！';
        }
        else{
            $rs['msg'] = $user->getError();
        }

        return $rs;
    }


    public function addUsers($userdata)
    {

        $oid =0;
        $user = $this;


        $rs = [];

        foreach($userdata as $j){
            $j['oid'] = $oid;
            if($j['sex'] == '男')
                $j['sex'] = 'male';
            else
                $j['sex'] = 'female';

            if($user->create($j)){
                $user->add();
                $rs['code'] = 1;
                $rs['msg'] = $j['username']."："."添加成功";
            }
            else{
                $rs['code'] = -1;
                $rs['msg'] = $j['username']."：".$user->getError();
                return $rs;
            }
        }

        return $rs;
    }



    /**
     * 批量组织添加用户，返回操作结果数组
     * @param $userjsondata
     * @param $classjsondata
     * @return array
     */

    public function addOrgnizerUsers($userdata, $classjsondata, $oid)
    {


        $user = $this;
        $user_class = M('orgnizeruserclass');

        $rs = [];

        foreach($userdata as $j){
            $j['oid'] = $oid;
            if($j['sex'] == '男')
                $j['sex'] = 'male';
            else
                $j['sex'] = 'female';

            if($user->create($j)){
                $uid = $user->add();
                if ($user_class->add(['oid' => $oid, 'class' => $classjsondata, 'uid' => $uid])){
                    $rs['code'] = 1;
                    $rs['msg'] = '操作成功！';
                }
                else{
                    $rs['code'] = -1;
                    $rs['msg'] = $user_class->getError();
                    return $rs;
                }
            }
            else{
                $rs['code'] = -1;
                $rs['msg'] = $j['username']."：".$user->getError();
                return $rs;
            }
        }

        return $rs;
    }

    /**
     * 批量删除用户
     * @param $userlist
     * @return array
     */

    public function deleteUsers($userlist)
    {
        $User = $this;

        foreach($userlist as $u){
            $User->relation(true)->delete($u['uid']);
        }


        $rs['msg'] = '批量删除用户完成！';
        $rs['code'] = 1;

        return $rs;
        //$this->ajaxReturn($rs);
    }


}